package com.lance.answer.gui.answer.gk.answer;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.GkUserCourseInfo;
import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.section_import.SectionImport;
import com.lance.answer.util.CollectionsUtil;
import com.lance.answer.util.Constant;
import com.lance.answer.util.MD5Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;

/**
 * <p>获取每门课程的所有链接 包括上传文件、创建话题、做题<p>
 *
 *
 *
 *
 * 工程经济,size:1
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2021/7/15 14:47
 */
public class GetCourseInfoByTeacher {

    public static void login(WebDriver driver, String userName, String pwd) {
        WebElement agreeButton = driver.findElement(By.id("RememberLogin"));
        agreeButton.click();

        WebElement userNameInput = driver.findElement(By.id("username"));
        userNameInput.clear();
        userNameInput.sendKeys(userName);

        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.clear();
        passwordInput.sendKeys(pwd);


        WebElement loginBtn = driver.findElement(By.name("button"));

        loginBtn.click();
    }

    public static void main(String[] args) throws Exception {
        ChromeDriver driver = Util.getDriver(null);
        String url = "http://thome.ouchn.cn/";
        driver.get(url);
        Thread.sleep(5000);
//        String userName = "xj_zhishu115";
//        String pwd = "zsxy123456WY";
        String userName = "zsxypy_6";
        String pwd = "zsxypy_6";

        Map<String, String> SUBJECT = Constant.SUBJECT;


        for(File d:new File("libs//userCourseInfo").listFiles()){
            if(!d.isDirectory()){
                continue;
            }
            for(File file:d.listFiles()){
                InputStream inputStream = new FileInputStream(file);
                String courseInfoStr = IOUtils.toString(inputStream, "UTF-8");
                List<GkUserCourseInfo> list = JSONObject.parseArray(courseInfoStr, GkUserCourseInfo.class);
                for(GkUserCourseInfo courseInfo:list){

                    if(!SUBJECT.containsValue(courseInfo.getCourseName())){
                        System.err.println("courseInfo:"+courseInfo);
                        SUBJECT.put(courseInfo.getCourseName(),courseInfo.getCourseName());
                    }

                }
            }
        }

     //   Thread.sleep(100000000);

        login(driver, userName, pwd);

        Thread.sleep(1000);
        Util.switchToFirst(driver);

        // d://newAnswer//
        List<String> names = Lists.newArrayList();
        for(File f1:new File("libs//courseUrlInfo").listFiles()){
            System.err.println(">>>>>"+f1);
            String name = f1.getName();

            InputStream userInputStream = new FileInputStream(f1);
            List<String> urlString = IOUtils.readLines(userInputStream, "utf-8");
            Set<String> urlTask = Sets.newHashSet();
            for(String urlInfo:urlTask){
                if(Strings.isNullOrEmpty(urlInfo)){
                    continue;
                }
                if (urlInfo.contains("形考")
                        || urlInfo.contains("作业")
                        || urlInfo.contains("专题测验")
                        || urlInfo.contains("专题检验")
                        || urlInfo.contains("单元测试")
                        || urlInfo.contains("考核")
                        //  || urlInfo.contains("测试（")
                        || urlInfo.contains("材料分析题（")
                        || urlInfo.contains("综合记分作业")
                ){
                    urlTask.add(urlInfo);
                }
            }
            // 这里还需要判断是否有三个形考任务，才加进去
          // if(urlTask.size()>3){
           if(urlTask.size()>-1){
               names.add(name.substring(0,name.length()-4));
           }
        }

        for (String id : SUBJECT.keySet()) {
            if(names.contains(SUBJECT.get(id))){
                 continue;
            }
            if(SUBJECT.get(id).contains("机械CAD")){
                continue;
            }
            try {
                driver.get("http://thome.ouchn.cn/");
                Thread.sleep(2000);
                String subjectName = SUBJECT.get(id);

                driver.findElement(By.id("txtclassname")).sendKeys(subjectName);
                driver.findElement(By.className("btnblue_m")).click();
                Thread.sleep(5000);

              List<WebElement> webElements =  new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
                        d -> d.findElements(By.tagName("tr")));
              if(webElements.isEmpty()){
                  continue;
              }

              boolean isContinue = false;
                for (WebElement we : webElements) {
                    // 第一个TH是课程编号
                    if (Util.findByTagName(we, "td") == null) {
                        continue;
                    }
                    System.err.println("we.findElement(By.tagName(\"td\")).getText()):" + we.findElement(By.tagName("td")).getText());
                    if (!id.equals(we.findElement(By.tagName("td")).getText())) {
                        continue;
                    }
                    we.findElement(By.tagName("a")).click();
                    isContinue = true;
                    break;
                }
                Thread.sleep(5000);
                // ------------FIXME ----
                if(!isContinue){
                    continue;
                }

                // 关闭其他页面，只留下当前课程页面
                Util.switchToFirst(driver);
                driver.close();
                Thread.sleep(2000);
                Util.switchToFirst(driver);

                Set<Cookie> cookies = driver.manage().getCookies();
                String token = "";
                for (Cookie c : cookies) {
                    if("MoodleSession".equals(c.getName())){
                        token = c.getValue();
                    }
                }
                System.err.println("token:"+token);
                //

                Document doc = SectionImport.getDocument(driver.getCurrentUrl(),userName,token);
                Elements courses = doc.getElementsByClass("course-content");
                //System.out.println(courses.toString());

                if (CollectionsUtil.isEmpty(courses)) {
                    System.out.println("为空");
                    return;
                }
                Element course = courses.get(0);
                int sectionCount = 200;
                List<String> lines = new ArrayList<>();
                for (int i = 2;i <= sectionCount;i++) {
                    Element section = course.getElementById("section-" + i);
                    //System.out.println(section.toString());
                    if (null != section) {
                        Elements instances = section.select("a[class=aalink]");
                        for (Element instance:instances) {
                            String href = instance.attr("href");
                            String instanceName = instance.getElementsByClass("instancename").get(0).ownText();
                            String line = String.format("%s,%s",href,instanceName);
                            System.out.println(line);
                            // FIXME
//                            if(line.contains("形考任务")){
//                                lines.add(line);
//                            }
                            lines.add(line);
                            // FIXME
                        }
                        System.out.println("\n");
                        System.out.println("\n");
                        System.out.println("-----------------------------------------");
                    }
                }
                File file = new File("libs//courseUrlInfo//"+subjectName+".txt");
                FileUtils.writeLines(file,lines);

                Thread.sleep(2000);

              //  FileUtils.write(new File("d://newAnswer//" + subjectName + ".json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        Thread.sleep(2000);
        driver.quit();
    }
}
